using System.Collections;
using System.Collections.Generic;

namespace FakeGameEngine
{

    public class GameObject
    {
        public bool IsActive = true;
        public readonly HashSet<Coroutine> Coroutines = new HashSet<Coroutine>();

        public GameObject() { }

        public virtual void Awake() { }
        public virtual void Update() { }

        public Coroutine StartCoroutine(IEnumerator enumerator)
        {
            Coroutine coroutine = new Coroutine(this) { Enumerator = enumerator };

            if (!enumerator.MoveNext())
            {
                return coroutine;
            }

            coroutine.LastFrame = Time.FrameCount;
            Coroutines.Add(coroutine);
            return coroutine;
        }

        public Coroutine StartCoroutine(YieldInstruction enumerator)
        {
            Coroutine coroutine = new Coroutine(this) { Enumerator = enumerator };
        }

        public void StopCoroutine(Coroutine coroutine)
        {
            if (Coroutines.Contains(coroutine))
                Coroutines.Remove(coroutine);
        }

        #region  for GameEngine

        private bool _awaked = false;
        public void CheckAwake()
        {
            if (_awaked || !IsActive)
                return;
            _awaked = true;
            Awake();
        }

        public void YieldNull()
        {
            foreach (var coroutine in Coroutines)
            {
                if (coroutine.LastFrame == Time.FrameCount)
                    continue;
                if (!coroutine.Enumerator.MoveNext())
                    Coroutines.Remove(coroutine);

                coroutine.LastFrame = Time.FrameCount;
            }
        }
        #endregion
    }

}